import gc
import time
import numpy as np
import Draw
import Export
import MOGRO
import MOLSO
import MOPSO
import config
import db
import random

# 按间距中的绿色按钮以运行脚本。
import file

if __name__ == '__main__':
    exp_data = []
    tasks = db.init_course_task()  # taskdata存储即将进行排课的教学任务
    # 根据选课信息表中的信息将学生信息筛选出，确定学生信息
    student_list = db.init_sel_students()  # 存储选课学生的信息
    teacher_list = db.init_sel_teachers()
    students = [student_list[i][0] for i in range(len(student_list))]
    teachers = [teacher_list[i][0] for i in range(len(teacher_list))]
    # 存储授课老师信息
    classrooms = db.init_classrooms()  # 教室列表信息
    buildings_dis = db.init_buildingDistance()  # 教学楼距离列表信息
    for _ in range(10):
        start = time.time()
        results, results_fit, x, y1, y2, y3, RTlino_g = MOPSO.MOPSO(tasks, students, teachers, classrooms,
                                                                buildings_dis)

        # 选出最优方案
        # print("学生教师方差：", results_fit[1], "教室空闲率：", results_fit[2], "平均距离：", results_fit[3])
        # end = time.process_time()  # 结束运行时间
        end = time.time()  # 结束运行时间
        total_time = end - start
        print("运行时间: %.03f seconds" % total_time)  # 运行时间 : 2.999 seconds
        weight_sum = [config.s_t_weight * y1[i] + config.r_weight * y2[i] + config.s_t_dis_weight * y3[i] for i in range(len(y1))]
        min_index = weight_sum.index(min(weight_sum))
        # 选出最优方案
        print("第", _+1, "次实验：","学生教师方差：", y1[min_index], "教室空闲率：", y2[min_index], "平均距离：", y3[min_index])
        exp_data.append(
            [config.particals, config.MaxIter, config.step_factory, total_time, y1[min_index], y2[min_index],
             y3[min_index], round(min(weight_sum), 2)])
        # file.save_scheme(results)  # 将最优解存入文件“排课结果.xlsx”中
        # Export.export_toDB(results)
            #
            # # The End time
            # Draw.fitness_line(x, y1, y2, y3)
        del results, results_fit, x, y1, y2, y3, RTlino_g, start, end, weight_sum, min_index
        gc.collect()
        file.save_data(exp_data)

    del exp_data, tasks, student_list, teacher_list, students, teachers, classrooms, buildings_dis, _
    gc.collect()
